package com.teemo.equipment.config;

import com.teemo.equipment.domain.vo.ResultVO;
import com.teemo.equipment.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author Teemo
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandlerAdvice {

    @ExceptionHandler(BizException.class)
    public ResponseEntity handleBizException(BizException e) {
        log.error("系统异常", e);
        return ResponseEntity.ok(ResultVO.fail(e.getMessage()));
    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity handleBindException(BindException e) {
        log.error("参数绑定异常", e);
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = Optional.ofNullable(allErrors).orElse(new ArrayList<>())
                .stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                .filter(Objects::nonNull).sorted().findFirst().orElse(e.getMessage());


        return ResponseEntity.ok(ResultVO.fail(message));
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("请求方式异常", e);
        return ResponseEntity.ok(ResultVO.fail("请求方式不允许"));
    }


    @ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception e) {
        log.error("系统异常", e);
        return ResponseEntity.ok(ResultVO.fail(e.getMessage()));
    }
}
